using System;
using UnityEngine;

namespace Managers
{
    [Serializable]
    internal class Statistic
    {
        public int bestScore;
        public int deathCount;
        public int playTime;
    }
    
    [CreateAssetMenu(fileName = "StatisticManager", menuName = "ScriptableObjects/StatisticManager")]
    public class StatisticManager : ScriptableObject
    {
        private Statistic _statistic = new();

        private void OnEnable()
        {
            _statistic.bestScore = PlayerPrefs.GetInt("bestScore", 0);
            _statistic.deathCount = PlayerPrefs.GetInt("deathCount", 0);
            _statistic.playTime = PlayerPrefs.GetInt("playTime", 0);
        }

        public void ResetStatistic()
        {
            _statistic.bestScore = 0;
            _statistic.deathCount = 0;
            _statistic.playTime = 0;
            PlayerPrefs.DeleteAll();
        }

        public void SaveStatistic()
        {
            PlayerPrefs.SetInt("bestScore", _statistic.bestScore);
            PlayerPrefs.SetInt("deathCount", _statistic.deathCount);
            PlayerPrefs.SetInt("playTime", _statistic.playTime);
        }
        
        public void SetBestScore(int bestScore)
        {
            if (_statistic.bestScore < bestScore)
            {
                _statistic.bestScore = bestScore;
            }
        }
        
        public void IncreaseDeathCount()
        {
            _statistic.deathCount += 1;
        }
        
        /// <exception cref="ArgumentOutOfRangeException">поднимается, если `playTime` отрицательный</exception>
        public void IncreasePlayTime(int deltaPlayTime)
        {
            if (deltaPlayTime < 0)
                throw new ArgumentOutOfRangeException(nameof(deltaPlayTime));
            _statistic.playTime += deltaPlayTime;
        }

        public string GetStatisticAsJson()
        {
            return JsonUtility.ToJson(_statistic);
        }
    }
}
